package CutLoad.components {
	import CutLoad.Base;
	import CutLoad.cookies.Painter;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.media.SoundTransform;
	import flash.media.Video;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	/**
	 *  
	 * 视频显示对象
	 * @author smallerbird mail:smallerbird@gmail.com  site:www.mkigm.com QQ群:49983196
	 * 
	 */	
	public class CVideoDisplay extends Base {
		private var videoURL:String;
		private var connection:NetConnection;
		private var stream:NetStream=null;
		//视频准备好时，视频错误时
		private var funCompt:Function,funError:Function;
		//播放结束
		private var funPlayEnd:Function;
		//播放结速
		private var funStop:Function
		private var isAutoPlay:Boolean;
		private var videoInfo:Object=null;
		private var video:Video;
		private var videoWidth:Number,videoHeight:Number;
		//视频的宽高比
		private var videoWHR:Number;
		//背景
		private var bak:Base;
		//
		private var vw:Number,vh:Number;
		/**
		 * 初始化 
		 * @param videoURL 视频地址
		 * @param funCompt 连接到视频时的回调方法 格式:function(me:CVideoDisplay)
		 * @param funPlayEnd 停止播放时的回调方法 格式:function(me:CVideoDisplay)
		 * @param vw 视频的高
		 * @param vh 视频的宽
		 * @param funError 视频连接错误的回调方法
		 * @param isAutoPlay 是否自动播放
		 * 
		 */		
		public function CVideoDisplay(videoURL:String,funCompt:Function,funPlayEnd:Function=null,vw:Number=0,vh:Number=0,funError:Function=null,isAutoPlay:Boolean=true) {
			this.mouseChildren=false;
			this.isAutoPlay=isAutoPlay;
			this.funCompt=funCompt;
			if(funError==null){
				funError=function(me:CVideoDisplay,type:Number):void{}
			}
			this.funError=funError;
			//
			if(funPlayEnd==null){
				funPlayEnd=function(me:CVideoDisplay):void{}
			}
			this.funPlayEnd=funPlayEnd;
			this.videoURL=videoURL;
			connection = new NetConnection();
			connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			connection.connect(null);
			//
			videoWidth=0;
			videoHeight=0;
			//
			this.vw=vw;
			this.vh=vh;
			setBakColor(0x000000,1);
			videoWHR=0;
		}
		protected function netStatusHandler(e:NetStatusEvent):void {
			trace("netStatusHandler:"+e.info.code);
			switch(e.info.code){
				case "NetConnection.Connect.Success":
					connectStream();
					break;
				case "NetStream.Play.StreamNotFound":
					//"错误：视频文件地址无法访问"
					this.funError(this,1);
					break;
				case "NetStream.Play.Failed":
					//"错误：视频播放失败"
					this.funError(this,2);
					break;
				//case "NetStream.Play.Start":
					//"播放已开始";
					//break;
				case "NetStream.Buffer.Empty":
					//"影片缓冲中...";
					break;
				case "NetStream.Play.Stop":
					trace("NetStream.Play.Stop:"+Math.floor(stream.time)+"::"+Math.floor(this.videoInfo.duration))
					//"播放已停止";
					if(Math.floor(stream.time)>=Math.floor(this.videoInfo.duration)){
						try{
							funPlayEnd(this)
						}catch(e:ArgumentError){
							funPlayEnd()
						}
					}
					break;
				case "NetStream.Seek.InvalidTime":
					//"错误：无法跳到指定的时间点播放";	
					this.funError(this,3);
					break;	
				default:
					break;
			}
		}
		protected function securityErrorHandler(event:SecurityErrorEvent):void {
			//trace("securityErrorHandler: " + event);
			this.funError(this,4);
		}
		private function connectStream():void {
			var ME:CVideoDisplay=this;
			stream = new NetStream(connection);
			var obj123:Object=new Object();
			obj123.onPlayStatus=function(data:Object):void{
				//trace("onPlayStatus..");
			}
			obj123.onMetaData=function(data:Object):void{
				//trace("onMetaData");
				videoInfo=data;
				/*this.videoInfo={
					canSeekToEnd:data.canSeekToEnd,
					videocodecid:data.videocodecid, 
					framerate:data.framerate, 
					videodatarate:data.videodatarate, 
					height:data.height,
					width:data.width, 
					duration:data.duration
				}*/
				videoWidth=data.width
				videoHeight=data.height
				videoWHR=data.width/data.height
				if(vw==0&&vh==0){
					setWH(data.width,data.height);
				}else{
					setWH();
				}
				//视频准备成功。。
				try{
					funCompt(ME);
				}catch(e:ArgumentError){
					funCompt();
				}
				//trace("2");
			}
			stream.client=obj123;
			stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			//stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
			video= new Video();
			video.attachNetStream(stream);
			addChild(video);
			chekVideoBakIndex()
			if(isAutoPlay) play();
			//trace("1");
		}
		private function asyncErrorHandler(event:AsyncErrorEvent):void {
			// ignore AsyncErrorEvent events.
		}
		//是否准备好
		protected function noReady():void{
			if(stream==null) throw new Error("video no ready..");
		}
		//检测video与bak的深度值
		private function chekVideoBakIndex():void{
			if(video==null) return;
			if(bak==null) return;
			if(this.getChildIndex(video)<this.getChildIndex(this.bak)){
				this.swapChildren(video,bak);
			}
		}
		/**
		 * 设置音量 
		 * @param vol
		 * 
		 */		
		public function SetVolumn(vol:Number):void {
			noReady()
			var _snd:SoundTransform = stream.soundTransform;
			_snd.volume = vol;
			stream.soundTransform = _snd;
		}
		/**
		 * 播放 
		 * @param offset 从哪里开始，以秒为单位
		 * 
		 */		
		public function play(offset:Number=0):void{
			noReady();
			if(offset==0){
				//trace("stream.time::"+stream.time);
				if(stream.time!=0){
					stream.seek(stream.time);
				}else{
					stream.play(videoURL);
				}
			}else{
				stream.seek(offset);
			}
			stream.resume();
		}
		/**
		 * 暂停 
		 * 
		 */		
		public function pause():void{
			noReady();
			stream.pause();
		}
		/**
		 * 设置背景色 
		 * @param c 背景色
		 * @param a 透明度
		 * 
		 */		
		public function setBakColor(c:Number,a:Number=1):void{
			if(bak!=null){
				this.bak.killMe();
				bak=null;	
			}
			this.bak=Painter.drawRect(vw,vh,c,a)
			bak.show(this);	
			if(this.getChildIndex(video)<this.getChildIndex(this.bak)){
				this.swapChildren(video,bak);
			}
			chekVideoBakIndex()
		}
		/**
		 * 获得视频信息 
		 * @return 
		 * 
		 */		
		public function getVideoInfo():Object{
			if(videoInfo==null) return null;
			return this.videoInfo;
		}
		/**
		 * 获得视频 NetStream对象
		 * @return 
		 * 
		 */		
		public function getStream():NetStream{
			return this.stream;
		}
		/**
		 * 设置宽高 
		 * @param w
		 * @param h
		 * 
		 */		
		override public function setWH(w:Number=0, h:Number=0):void{
			if(w!=0){
				vw=w;
			}
			if(h!=0){
				vh=h;
			}
			autoVideoWH();
			this.setBakColor(0x000000,1);
		}
		//视频等比缩放
		private function autoVideoWH(isAlignCenter:Boolean=true):void{
			if(video==null) return;
			if(videoWHR==0) return;
			if(this.videoWidth==0||videoHeight==0) return;
			video.x=0;
			video.y=0;
			if(this.videoWidth>this.videoHeight){
				video.width=vw;
				video.height=video.width/videoWHR;
				if(isAlignCenter){
					video.y=(vh-video.height)/2
				}
			}else if(this.videoWidth<this.videoHeight){
				video.height=vh;
				video.width=video.height*videoWHR;
				if(isAlignCenter){
					video.x=(vw-video.width)/2;
				}
			}else{
				video.width=vw;
				video.height=vh;
			}
		}
		/**
		 * 根据视频的比例，自动适应设置的高或宽，多出的背景部份。例如你设置的宽度为:100*50 而视频为800*600 则显示的实际的尺寸为100*(800/(800/600)); 
		 * @param w 设置的高
		 * @param h 设置的宽
		 * 
		 */		
		public function setWHAutoFullSize(w:Number,h:Number):void{
			if(w<=0) return;
			if(h<=0) return;
			vw=w;
			vh=h;
			autoVideoWH(false);
			vw=video.width;
			vh=video.height;
			this.setBakColor(0x000000,1);
		}
		/**
		 * 获得宽度 
		 * @return 
		 * 
		 */		
		override public function getShowWidth():Number{
			return vw;
		}
		/**
		 * 获得高度 
		 * @return 
		 * 
		 */		
		override public function getShowHeight():Number{
			return vh
		}
		override public function killMe():void{
			if(connection!=null){
				connection.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
				connection.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
				connection=null;
			}
			if(stream!=null){
				stream.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
				stream.close();
				stream=null;
			}
			if(video!=null){
				this.removeChild(video);
			}	
			super.killMe();
		}
	}
}
